/**
 * ReportGear(2011)
 */
package com.reportgear.report.model.calculator;

import java.util.Iterator;

import com.reportgear.report.context.ReportContext;
import com.reportgear.report.model.ReportModel;
import com.reportgear.report.model.cell.Cell;
import com.reportgear.report.model.cell.value.salary.SalaryMainObject;
import com.reportgear.report.model.cell.value.support.CommonObject;
import com.sot.core.util.StringUtils;

/**
 * 
 * 薪酬对象分组计算
 * 
 * @version 1.0 2011-4-10
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class SalaryObjectGroupCalculator extends AbstractCalculator {
	public SalaryObjectGroupCalculator() {

	}

	@Override
	public ReportModel calculate(ReportModel model, CalcParameter parameter) {
		if (logger.isDebugEnabled()) {
			logger.debug("计算模型：薪酬对象分组计算");
		}

		ReportModel calcModel = model;
		int groupLevel = parameter.getGroupLevel();

		Iterator<Cell> cells = calcModel.getCellsIteratorByCellElementClass(SalaryMainObject.class);

		if (groupLevel > 0) {
			for (Iterator<Cell> i = cells; i.hasNext();) {
				Cell cell = i.next();
				SalaryMainObject smo = (SalaryMainObject) cell.getValue();
				CommonObject co = smo.getObject();

				int row = cell.getRow();
				if (row > 0) {
					int col = cell.getColumn();
					Cell prev = calcModel.getCell(col, row - 1);

					Object prevValue = prev.getValue();
					if (prevValue instanceof SalaryMainObject) {
						if (this.getCodeLevel(co.getCode()) == groupLevel) {
							model.getRowPropList().setGroup(row, true);
						}
					}
				}
			}
		}

		return calcModel;
	}

	public int getCodeLevel(String code) {
		if (StringUtils.isEmpty(code)) {
			return 0;
		} else {
			return code.split("-").length;
		}
	}
}
